/**
 * Created by macos on 14/11/11.
 */
var query = require('querystring');

(function(){
    var root = this;
    var AuthorizationController = {};

    function authLogin(next){
        var req =root.request;
        var res =root.response;

        if(req.session.user){
            return next();
        }
        if(req.method == 'GET'){
            var html = [
                '登录授权',
                '<form method="POST">',
                '用户名:<input type="input" name="username"  />',
                '密&nbsp;&nbsp;码:<input type="password" name="password"  />',
                '<input type="submit" value="登录授权" />',
                '</form>'
            ];
            return res.send(html.join('<br/>'));
        }
        var username = req.body.username;
        var password = req.body.password;
        if(!username||!password){
            var html = [
                '登录授权',
                '<form method="POST">',
                '用户名;<input type="input" name="username"  />',
                '密码;<input type="input" name="password"  />',
                '<input type="submit" value="登录授权" />',
                '</form>'
            ];
            return res.send(html.join('<br/>'));
        }

        User.findOne({username:username,password:password})
            .exec(function(err,result){
                if(err){
                    sails.log.error(err);
                    return next(err);
                }
                if(_.has(result,"id")){
                    req.session.user=result;
                    return next();
                }
         });

    }

    function userauth(next){
        var req =root.request;
        var res =root.response;
        var decision = req.body.decision;
        if(!decision){
            var html = [
                    'Currently your are logged with id = ' + req.session.user.username,
                    'Service with id ' + req.body.serviceName + ' asks for access',

                '<form method="POST">',
                '<input type="hidden" name="decision" value="1" />',
                '<input type="submit" value="Authorize" />',
                '</form>',
                '<form method="POST">',
                '<input type="hidden" name="decision" value="0" />',
                '<input type="submit" value="Cancel" />',
                '</form>'
            ];
            return res.send(html.join('<br />'));
        }
        if (!req.body || typeof(req.body['decision']) == 'undefined')
            return next("No decision parameter passed");
        else if (req.body['decision'] == 0)
            return next("User denied the access to the resource");
        else {
            delete req.body.decision;
            return  next();
        }

    }

    function createAuthorization(next){
        var req =root.request;
        req.body.userId = req.session.user.id;
        req.body.username = req.session.user.username;
        Authorization.create(req.body)
            .exec(function(err,result){
                if(err){
                    sails.log.error(err);
                    return next(err);
                }
                next(null,result);
            });
    }

    function createToken(next){
        var reqJson =root.request.body;
        var redirectUri = reqJson.redirectUri;
        delete reqJson.redirectUri
        reqJson.grantType="implicit";
        reqJson.userId=root.request.session.user.id;
        AccessToken.create(reqJson)
            .exec(function(err, result){
                //..
                if(err){
                    sails.log.error(err);
                    return next(err);
                }
                result.redirectUri = redirectUri;
                next(null, result);
            });
    }

    AuthorizationController.index = function(req, res) {
        root.request = req;
        root.response = res;

        if(!req.body){
            req.body = {};
        }
        if(!req.body.responseType){
            req.body.responseType = req.query.responseType;
        }
        if(!req.body.redirectUri){
            req.body.redirectUri = req.query.redirectUri;
        }
        if(!req.body.serviceName){
            req.body.serviceName = req.query.serviceName;
        }
        if(!req.body.decision){
            req.body.decision = req.query.decision?req.query.decision:req.param("decision");
        }

        if (req.body.responseType === 'code') {
            async.waterfall([
                //...
                authLogin,
                userauth,
                createAuthorization
            ], function(err, result) {
                if (err) {

                    if (_.has(err, 'status')) {
                        return res.jsonResponse(err.status, err.message);
                    } else {
                        return res.jsonResponse(403, err);
                    }
                }
                //...
                return res.redirect(req.body.redirectUri+"?code="+result.code);
            })

        } else if (req.body.responseType === 'token') {
            //...
            async.waterfall([
                authLogin,
                userauth,
                createToken
            ], function(err, result) {
                if (err) {

                    if (_.has(err, 'status')) {
                        return res.jsonResponse(err.status, err.message);
                    } else {
                        return res.jsonResponse(403, err);
                    }
                }
              //...
                return res.redirect(result.redirectUri+"#token_type="+result.tokenType+"&token="+result.accessToken+"&expires_in="+(result.expiresTime-new Date().getTime()));
            })

        }

        else {
            return res.jsonResponse(404, "responseType not found!");
        }
    }

    module.exports = AuthorizationController;
})();

